define(['jquery', 'bootstrap', 'utilback', 'table', 'form'], function ($, undefined, Utilback, Table, Form) {

    var Controller = {
    	config: {
    		get_dic: '/dic/read/detail',
    		get_param: '/param/read/detail',
    	},
        init: function () {
            this.initDic();
            this.initParam();
            this.initTask();
            this.initMsgConfig();
        },
        initDic: function() {
        	$('[href="#dic"]').on('click', function() {
                // 初始化表格参数配置
                Table.api.init({
                	singleSelect: true,
                    extend: {
                        index_url: '/dic/read/page',
                        add_url: 'dicEdit.html',
                        edit_url: 'dicEdit.html',
                        del_url: '/dic',
                        multi_url: '/dic',
                    }
                });
            });
            $('[href="#dic"]').click();
            var dicTable = $("#dicTable");
            // 初始化表格
            dicTable.bootstrapTable({
            	toolbar: '#toolbar1',
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                  	    {field: 'type', title: '类型'},
                        {field: 'codeText', title: '选项描述'},
                        {field: 'code', title: '选项值'},
                        {field: 'sortNo', title: '排序'},
                        {field: 'updateTime', title: '修改时间'},
                        {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: function (value, row, index) {
                            return Table.api.formatter.operate.call(this, value, row, index, dicTable);
                        }}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(dicTable);
        },
        initParam: function() {
        	var i = 0;
            $('[href="#param"]').on('click', function() {
            	// 初始化表格参数配置
                Table.api.init({
                	singleSelect: true,
                    extend: {
                        index_url: '/param/read/list',
                        add_url: 'paramEdit.html',
                        edit_url: 'paramEdit.html',
                        del_url: '/param',
                        multi_url: '/param',
                    }
                });
            	if(i === 0) {
                    var paramTable = $("#paramTable");
                    // 初始化表格
                    paramTable.bootstrapTable({
                    	toolbar: '#toolbar2',
                        url: $.fn.bootstrapTable.defaults.extend.index_url,
                        columns: [
                            [
                                {field: 'state', checkbox: true, },
                                {field: 'id', title: 'ID'},
                          	    {field: 'paramKey', title: '参数键'},
                                {field: 'paramValue', title: '参数值'},
                                {field: 'remark', title: '备注'},
                                {field: 'updateTime', title: '修改时间'},
                                {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: function (value, row, index) {
                                    return Table.api.formatter.operate.call(this, value, row, index, paramTable);
                                }}
                            ]
                        ]
                    });
                    // 为表格绑定事件
                    Table.api.bindevent(paramTable);
                    i++;
            	}
            });
        },
        initTask: function() {
        	var i = 0;
            var taskTable = $("#taskTable");
        	$('[href="#task"]').on('click', function() {
            	// 初始化表格参数配置
                Table.api.init({
                	singleSelect: true,
                    extend: {
                        index_url: '/scheduled/read/tasks',
                        add_url: 'taskEdit.html',
                        del_url: '/scheduled',
                        multi_url: '/scheduled',
                    }
                });
            	if(i === 0) {
                    // 初始化表格
                    taskTable.bootstrapTable({
                    	toolbar: '#toolbar3',
                        url: $.fn.bootstrapTable.defaults.extend.index_url,
                        pk: 'taskName',
                        columns: [
                            [
                                {field: 'state', checkbox: true, },
                                {field: 'targetSystem', title: '所属系统'},
                                {field: 'taskDesc', title: '名称'},
                          	    {field: 'targetObject', title: '执行代码', formatter: function (value, row, index) {
                          	    	 if(row.targetObject && row.targetMethod)
                              		   return  row.targetObject + '.' + row.targetMethod;
                              	   return '';
                          	    }},
                                {field: 'taskCron', title: '频率'},
                                {field: 'nextFireTime', title: '运行时间'},
                                {field: 'previousFireTime', title: '最后运行'},
                                {field: 'status', title: '状态', formatter: function(data, type, row) {
                                  	switch(data) {
                                  	case 'NORMAL':
                                  		return '<span class="label label-info">正常</span>';
                                  	case 'PAUSED':
                                  		return '<span class="label label-default">暂停</span>';
                                  	case 'COMPLETE':
                                  		return '<span class="label label-success">完成</span>';
                                  	case 'ERROR':
                                  		return '<span class="label label-warning">异常</span>';
                                  	case 'BLOCKED':
                                  		return '<span class="label label-danger">堵塞</span>';
                                  	}
                                  	return '';
                             }},
                                {field: 'contactName', title: '提醒给'}
                            ]
                        ]
                    });
                    // 为表格绑定事件
                    Table.api.bindevent(taskTable);
                	$('#toolbar3').on('click', '.btn-stop', function() {
                		var ids = Table.api.selectedids(taskTable);
                		operate('确定暂停?', '/scheduled/close', 'POST', '暂停成功.');
                	});
                	$('#toolbar3').on('click', '.btn-start', function() {
                		var ids = Table.api.selectedids(taskTable);
                		operate('确定启动?', '/scheduled/open', 'POST', '启动成功.');
                	});
                	$('#toolbar3').on('click', '.btn-run', function() {
                		operate('确定立即执行?', '/scheduled/run', 'POST', '执行成功.');
                	});
                	$('#toolbar3').on('click', '.btn-delone', function() {
                		operate('确定删除这条记录?', '/scheduled', 'DELETE', '删除成功.');
                	});
                	function operate(confirmMsg, url, type, noticeMsg) {
                		var ids = Table.api.selectedids(taskTable);
                		var params = JSON.stringify({taskGroup : 'ds_job', taskName: ids[0] });
                		var index =Layer.confirm(confirmMsg, {icon: 3, title: __('Warning'), shadeClose: true}, function() {
            	        	Util.api.ajax({
            	    			type : type,
            	    			url : url,
            	    			data : params
            	        	}, function(result) {
        	    				if (result.code == 200) {
        	    					Toastr.success(noticeMsg);
        	    				} else {
        	    					Toastr.error(result.msg);
        	    				}
        	    				taskTable.bootstrapTable('refresh');
        	    				$('.loading').hide();
            	    	   });
                            Layer.close(index);
                		});
                    }
                    i++;
            	}
            });
        },
        initMsgConfig: function() {
        	var i = 0;
        	$('[href="#msgConfig"]').on('click', function() {
            	if(i === 0) {
                    Form.api.bindevent($("form[role=form]"));
                	// 初始化表格参数配置
                    Util.api.ajax({
                      	type: 'PUT',
                      	url: '/msgConfig/read/list',
                      	data: JSON.stringify({pageSize: 1}),
                    }, function(result) {
          				if(result.rows.length > 0) {
          	  				var data = result.rows[0];
          	  				$('#msgConfigForm').autofill(data);
          	  				var k = ['orderIsSend', 'payIsSend', 'sendGoodsIsSend', 'registIsSend', 'adviceGoodsIsSend'];
          	  				for(var i=0; i<k.length;i++) {
          		  				if($('[name="' + k[i] + '"][value="' + data[k[i]] + '"]').length > 0) {
          		        			$('[name="' + k[i] + '"][value="' + data[k[i]] + '"]').get(0).checked = true;
          		        			$('[name="' + k[i] + '"][value="' + data[k[i]] + '"]').parents('span').addClass('checked');
          		  				}
          	  				}
          				}
                    });
                    i++;
            	}
            });
        },
        editDic: function () {
            Form.api.bindevent($("form[role=form]"));
    		var id = Util.api.query('id');
        	var t = Util.api.query('t');
        	if(id && t === 'U') {
        		Form.api.fill($('#edit-form'), Controller.config.get_dic, id, function(data) {
        		});
        	}
        },
        editParam: function () {
            Form.api.bindevent($("form[role=form]"));
    		var id = Util.api.query('id');
        	var t = Util.api.query('t');
        	if(id && t === 'U') {
        		Form.api.fill($('#edit-form'), Controller.config.get_param, id, function(data) {
        		});
        	}
        },
        editTask: function () {
            Form.api.bindevent($("form[role=form]"));
        	Util.api.ajax({
        		type: 'put',
        		data: JSON.stringify({}),
        		url: '/user/read/list'
        	}, function(rst) {
        		$('[name="contactName"]').html('');
                $('[name="contactName"]').append('<option value="">--请选择--</option>');
 				//将获取的数据添加到select选项中
 				$.each(rst.rows, function(n, row) {
                    $('[name="contactName"]').append('<option value="' + row.email + '">' + row.userName + '</option>');
				});
        	});
        }
    };
    return Controller;
});